﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using GsifWeb4.Models;
using System.Web.Mvc;
using System.Linq.Expressions;
using System.Web.Routing;
using System.Net.Mail;
using System.Security.Cryptography;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace GsifWeb4
{
    public static class UserManagement
    {
        public static bool ValidateUser(string username, string password, gsifdbEntities gsifDB)
        {
            string plainTextPassword = password;
            string encryptedPassword = Crypto.GetEncryptedValue(password);

            var userExists = (from u in gsifDB.laget_gsif
                              where u.Anvandarnamn == username && (u.Password == plainTextPassword || u.Password == encryptedPassword)
                              select u).FirstOrDefault();

            if (userExists != null)
                return true;

            return false;
        }

        public static bool PasswordStrengthOK(string password)
        {
            if (password.Trim().Length < 5)
                return false;

            return true;
        }
    }
    public static class Crypto
    {
        public static string GetEncryptedValue(string plainText)
        {
            string withSalt = "GSIF1993" + plainText;
            MD5 md5 = new MD5CryptoServiceProvider();
            Byte[] originalBytes = ASCIIEncoding.Default.GetBytes(withSalt);
            Byte[] encodedBytes = md5.ComputeHash(originalBytes);

            string result = BitConverter.ToString(encodedBytes);
            result = result.ToLower().Replace("-","");

            return (result);
        }
    }

    public static class MailHelper
    {
        public static bool SendMail(string toAdress, string subject, string text)
        {
            try
            {
                MailMessage msgMail = new MailMessage();

                MailMessage myMessage = new MailMessage();
                myMessage.From = new MailAddress("info@sahlmen.se", "Infos GSIF");
                myMessage.To.Add(toAdress);
                myMessage.Subject = subject;
                myMessage.IsBodyHtml = false;

                myMessage.Body = text;

                SmtpClient mySmtpClient = new SmtpClient();
                System.Net.NetworkCredential myCredential = new System.Net.NetworkCredential("info@sahlmen.se", "surfinewsb");
                mySmtpClient.Host = "smtp.sahlmen.se";
                mySmtpClient.UseDefaultCredentials = false;
                mySmtpClient.Credentials = myCredential;
                mySmtpClient.ServicePoint.MaxIdleTime = 1;

                mySmtpClient.Send(myMessage);
                myMessage.Dispose();
            }
            catch 
            {
                return false;
            }

            return true;
        }
    }

    public static class ExtensionMethods
    {
        public static List<string> ToStringList(this List<StatusValue> listWithStatusValues)
        {
            List<string> returnList = new List<string>();
            foreach (var statusValue in listWithStatusValues)
            {
                returnList.Add(statusValue.Text);
            }

            return returnList;
        }

        public static MvcHtmlString Label(this string expression, object htmlAttributes)
        {
            return Label(expression, new RouteValueDictionary(htmlAttributes));
        }

        public static MvcHtmlString Label(this string expression, IDictionary<string, object> htmlAttributes)
        {
            string labelText = expression;
            if (String.IsNullOrEmpty(labelText))
            {
                return MvcHtmlString.Empty;
            }

            TagBuilder tag = new TagBuilder("label");
            tag.MergeAttributes(htmlAttributes);
            //tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
            tag.SetInnerText(labelText);
            return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
        }
    }

   

    public class CalenderHelper
    {
        public class CalenderEvent
        {
            public enum EventType
            {
                Match = 0,
                Training = 1,
                Other = 2
            }

            public string Text { get; set; }
            public int Id { get; set; }
            public int TypeOfEvent { get; set; }
            public DateTime Date { get; set; }
        }

        public static List<DateTime> GetAllCalenderDates()
        {
            gsifdbEntities gsifDB = new gsifdbEntities();

            // List with all dates to show in calender
            List<DateTime> activeCalenderDates = new List<DateTime>();

            // Earliest activity to show in calender
            DateTime? minDate = (DateTime?)DateTime.Now.AddYears(-3);

            // ******* Add all match dates ********
            var matchDates = (from match in gsifDB.match_gsif
                              where match.Datum > minDate
                              select match.Datum).ToList();

            AddDateTimesToList(activeCalenderDates, matchDates);

            // ******* Add all training dates ********
            var trainingDates = (from training in gsifDB.traning_gsif
                                 where training.Datum > minDate
                                 select training.Datum).ToList();

            AddDateTimesToList(activeCalenderDates, trainingDates);

            // ******* Add all other dates ********
            var otherDates = (from other in gsifDB.ovrigt_gsif
                              where other.Datum > minDate
                              select other.Datum).ToList();

            AddDateTimesToList(activeCalenderDates, otherDates);

            return activeCalenderDates.OrderBy(d => d).Take(400).ToList();
        }

        private static void AddDateTimesToList(List<DateTime> dateList, List<DateTime?> datesToAdd)
        {
            foreach (var date in datesToAdd)
            {
                if (!date.HasValue)
                    continue;
                dateList.Add((DateTime)date);
            }
        }

    }

    public class CheckBoxItem
    {
        public string Name { get; set; }
        public string Text { get; set; }
        public bool Checked { get; set; }
    }

    public class SelectPlayerItem
    {
        public string Text { get; set; }
        public int Id { get; set; }

        public SelectPlayerItem(laget_gsif player)
        {
            Text = player.FNamn + " " + player.ENamn;
            Id = player.ID;
        }

        public SelectPlayerItem()
        {

        }
    }

    public class ImageHandler
    {
        public static Image ResizeImage(Image imgToResize, Size size)
        {
            //
            int sourceWidth = imgToResize.Width;
            int sourceHeight = imgToResize.Height;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = ((float)size.Width / (float)sourceWidth);
            nPercentH = ((float)size.Height / (float)sourceHeight);

            if (nPercentH < nPercentW)
                nPercent = nPercentH;
            else
                nPercent = nPercentW;

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap b = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage((Image)b);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
            g.Dispose();

            return (Image)b;
        }


        public static void SaveJpeg(string path, Bitmap img, long quality)
        {
            // Encoder parameter for image quality
            EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);

            // Jpeg image codec
            ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");

            if (jpegCodec == null)
                return;

            EncoderParameters encoderParams = new EncoderParameters(1);
            encoderParams.Param[0] = qualityParam;

            img.Save(path, jpegCodec, encoderParams);
        }

        private static ImageCodecInfo GetEncoderInfo(string mimeType)
        {
            // Get image codecs for all image formats
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

            // Find the correct image codec
            for (int i = 0; i < codecs.Length; i++)
                if (codecs[i].MimeType == mimeType)
                    return codecs[i];
            return null;
        }
    }

    public class Common
    {
        public static int GUEST_PLAYER_ID = -1;

        public static ovrigt_gsif GetOtherFromId(gsifdbEntities gsifDB, int id)
        {
            var otherEvent = (from other in gsifDB.ovrigt_gsif
                                 where other.OvId == id
                                 select other).SingleOrDefault();
            return otherEvent;
        }

        public static traning_gsif GetTrainingFromId(gsifdbEntities gsifDB, int id)
        {
            var trainingEvent = (from training in gsifDB.traning_gsif
                                 where training.TrId == id
                                 select training).SingleOrDefault();
            return trainingEvent;
        }

        public static match_gsif GetMatchFromId(gsifdbEntities gsifDB, int id)
        {
            var matchEvent = (from match in gsifDB.match_gsif
                              where match.MaId == id
                              select match).SingleOrDefault();
            return matchEvent;
        }

        public static laget_gsif GetPlayerFromUserName(gsifdbEntities gsifDB, string userName)
        {
            if (string.IsNullOrEmpty(userName))
                return null;

            var player = (from players in gsifDB.laget_gsif
                          where players.Anvandarnamn == userName
                          select players).SingleOrDefault();
            return player;
        }

        public static bool IsUserAllowedToBeWebred(gsifdbEntities gsifDB, string userName)
        {
            var player = GetPlayerFromUserName(gsifDB, userName);
            if (player == null)
                return false;

            return player.AllowedToWebRed();
        }

        public static bool IsCheckboxTrue(string checkboxValue)
        {
            return checkboxValue.ToLower().Contains("true");
        }

        public enum ForumTypes
        {
            Main = 0,
            HerrA = 1,
            HerrC = 2,
            DamA = 3,
            DamB = 4
        }

        // I tabellen statistik så finns en kolumn Typ som definierar vilken position som spelaren 
        // startade matchen. I gsif.nets begynnelse var dessa 1,2,3,4,5 men utökades sedan för att
        // kunna visa 4-4-2, 4-3-3 etc med 13, 21,22,23,24, 31,32 osv där första siffran talar om i
        // ifall det är målvakt, försvar etc medan andra talar om vilken position på tex mittfätet det är.
        public class StatisticMatchPosition
        {
            public static int GoalKeeper = 1;
            public static int Defender = 2;
            public static int Midfield = 3;
            public static int Forward = 4;
            public static int Substitute = 5;

            public static bool IsPosition(int number, int position)
            {
                return Convert.ToInt32(number.ToString().Substring(0, 1)) == position;
            }
        }

        public class WeekdayHelper
        {
            public static string GetWeekdayName(int day)
            {
                string[] weekdays = new string[] { "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag", "Söndag" };
                return weekdays[day];
            }
        }

        public class DropDownItem
        {
            public string Text { get; set; }
            public object Value  { get; set; }

            public DropDownItem(string text, object theValue)
            {
                Text = text;
                Value = theValue;
            }

            public DropDownItem(StatusValue statusValue)
            {
                Text = statusValue.Text;
                Value = statusValue.DbValue;
            } 
        }
    }
}

